package com.stox.manager;

import java.util.Timer;
import java.util.TimerTask;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stox.model.Country;
import com.stox.model.Exchange;

@Component
public class DownloadScheduleManager implements InitializingBean {

	@Autowired
	private DownloadManager downloadManager;
	
	@Autowired
	private CountryManager countryManager;
	
	@Autowired
	private ExchangeManager exchangeManager;
	
	private Timer timer = new Timer("Stox Download Scheduler", true);
	
	private TimerTask timerTask = new TimerTask(){
		@Override
		public void run() {
			for(Country country : countryManager.findAll()){
				for(Exchange exchange : exchangeManager.findByCountryCode(country.getCode())){
					downloadManager.bredthDownload(exchange);
				}
			}
		}
	};
	
	public DownloadScheduleManager() {
		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				if(null != timerTask)				timerTask.cancel();
				if(null != timer) 					timer.cancel();
				if(null != downloadManager)	downloadManager.cancel();
			}
		});
	}
	
	public void afterPropertiesSet() throws Exception {
		timer.schedule(timerTask, 0, 1000*60);
	}
	
}
